from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pathlib import Path
from ..utils.config import config

Base = declarative_base()

class ConvertibleBond(Base):
    """可转债信息表"""
    __tablename__ = 'convertible_bonds'

    id = Column(Integer, primary_key=True)
    bond_code = Column(String(10), unique=True, nullable=False, comment='转债代码')
    bond_name = Column(String(50), nullable=False, comment='转债名称')
    stock_code = Column(String(10), nullable=False, comment='正股代码')
    stock_name = Column(String(50), nullable=False, comment='正股名称')
    issue_date = Column(Date, nullable=True, comment='发行日期')
    apply_date = Column(Date, nullable=True, comment='申购日期')
    listing_date = Column(Date, nullable=True, comment='上市日期')
    delisting_date = Column(Date, nullable=True, comment='摘牌日期')
    issue_price = Column(Float, nullable=True, comment='发行价')
    issue_size = Column(Float, nullable=True, comment='发行规模（亿元）')
    convert_price = Column(Float, nullable=True, comment='转股价')
    convert_value = Column(Float, nullable=True, comment='转股价值')
    premium_rate = Column(Float, nullable=True, comment='转股溢价率')
    rating = Column(String(10), nullable=True, comment='评级')
    guarantee = Column(String(50), nullable=True, comment='担保情况')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def __repr__(self):
        return f"<ConvertibleBond(bond_code='{self.bond_code}', bond_name='{self.bond_name}')>"

class NotificationRecord(Base):
    """通知记录表"""
    __tablename__ = 'notification_records'

    id = Column(Integer, primary_key=True)
    bond_code = Column(String(10), nullable=False, comment='转债代码')
    notification_type = Column(String(20), nullable=False, comment='通知类型：email/wechat')
    status = Column(String(20), nullable=False, comment='通知状态：success/failed')
    error_message = Column(String(500), nullable=True, comment='错误信息')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')

    def __repr__(self):
        return f"<NotificationRecord(bond_code='{self.bond_code}', type='{self.notification_type}')>"

def init_db():
    """初始化数据库"""
    # 确保数据目录存在
    data_dir = Path(__file__).parent.parent.parent / 'data'
    data_dir.mkdir(exist_ok=True)
    
    # 创建数据库引擎
    engine = create_engine(config.get('database.url'))
    Base.metadata.create_all(engine)
    return sessionmaker(bind=engine)

# 创建Session工厂
Session = init_db() 